import axios from "axios";
import { Message } from "element-ui";
import router from "@/router";

const instance = axios.create({
    baseURL: "http://localhost:8080/api",
    // timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        let authUser = JSON.parse(sessionStorage.getItem("authUser"));
        if (authUser) {
            config.headers = {
                token: authUser.token,
            };
        }
        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

// 响应拦截器
instance.interceptors.response.use(
    (res) => {
        if (res.data.code == 401 && router.currentRoute.name != "login") {
            Message.error(res.data.data);
            sessionStorage.clear();
            router.push({ name: "login" });
            return Promise.reject();
        }
        return res;
    },
    (err) => {
        return Promise.reject(err);
    }
);

export default instance;
